package com.zzzzzz.topic.dao;

import java.util.List;

import org.bson.types.ObjectId;

import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.Query;
import com.mongodb.Mongo;
import com.zzzzzz.common.util.StringPool;
import com.zzzzzz.common.util.Validator;
import com.zzzzzz.core.dao.morphia.BaseDao;
import com.zzzzzz.core.exception.NoSuchTopicException;
import com.zzzzzz.topic.model.Topic;

public class TopicDao extends BaseDao<Topic, String> {

	public TopicDao(Mongo mongo, Morphia morphia, String dbName) {
		super(mongo, morphia, dbName);
	}
	
	private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No Topic exists with the primary key ";

	public void add(Topic topic) {
		save(topic);
	}

	public void edit(Topic topic) {
		Query<Topic> query = createQuery();
		query.filter("_id", ObjectId.massageToObjectId(topic.getTopicId()));
		update(query, createUpdateOperations()
				.set("description", topic.getDescription())
				.set("modifiedDate", topic.getModifiedDate())
		);
	}
	
	public void editStatus(String topicId, Integer status) {
		Query<Topic> query = createQuery();
		query.filter("_id", ObjectId.massageToObjectId(topicId));
		update(query, createUpdateOperations().set("status", status));
	}

	public Topic findById(String topicId) throws NoSuchTopicException {
		Topic topic = findOne("_id", ObjectId.massageToObjectId(topicId));
		if(topic == null) {
			throw new NoSuchTopicException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + topicId);
		}
		return topic;
	}
	
	public List<Topic> findAll(String category, int start, int offset, boolean ascending) {
		Query<Topic> query = createQuery();
		query.filter("status", 0);
		String condition = "createDate";
		if(!ascending) {
			condition = StringPool.DASH + condition;
		}
		if(Validator.isNotNull(category)) {
			query.filter("category", category);
		}
		query.limit(offset).offset(start).order(condition);
		return find(query).asList();
	}
	
	public long findAllCount() {
		Query<Topic> query = createQuery();
		query.filter("status", 0);
		return find(query).countAll();
	}
	
	public long findCountByCategory(String category) {
		Query<Topic> query = createQuery();
		query.filter("status", 0);
		if(Validator.isNotNull(category)) {
			query.filter("category", category);
		}
		return find(query).countAll();
	}
	
	public long findCountByUserId(String userId) {
		Query<Topic> query = createQuery();
		query.filter("status", 0);
		query.filter("userId", userId);
		return find(query).countAll();
	}

	public static final int ALL_POS = -1;
	
}
